package com.example.restful1.controller;

import com.example.restful1.model.Student;
import com.example.restful1.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class StudentController {

    @Autowired
    StudentService studentService;
    /**
     * 查询所有用户
     * @return
     */
    @CrossOrigin(origins = "http://localhost:8080")
    @GetMapping("/students")
    public List<Student> getAllStudents(){
        return studentService.list();
    }
    /**
     在 UserController 中一共定义了五个接口：
     1. Get 请求：/users，查询所有用户；
     2. Get 请求：/user/{id}，根据 id 查询指定用户；
     3. Post 请求：/user，添加用户；
     * 根据 id 查询指定用户
     * @param id
     * @return
     */
    @GetMapping("/studenet/{id}")
    public Student getUserById(@PathVariable("id") Integer id){
        Student student = studentService.getById(id);
        return student;
    }
    /**
     * 插入用户
     * @param student
     * @return
     */
    @PostMapping("/student")
    public String addUser(@RequestBody Student student){
        if (studentService.save(student)){
            return "插入用户成功！";
        }
        else return "插入用户失败";
    }
    /**
     * 修改用户信息
     * @param student
     * @return
     */
    @PutMapping("/student")
    public String updateUser(@RequestBody Student student){
        if (studentService.updateById(student)){
            return "更新用户成功！";
        }
        else return "更新用户失败";
    }
    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/student")
    public String deleteUserById(Integer id){
        if (studentService.removeById(id)){
            return "删除用户成功！";
        }
        else return "删除用户失败！";
    }
}
